package com.witmed.lib_base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

abstract class BaseFragment<V:ViewBinding,VM:BaseViewModel<*,*>>:Fragment() {

    lateinit var vm:VM
    lateinit var v:V

    abstract fun createVM():VM
    abstract fun createV():V
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vm=createVM()
        v=createV()
        initStateFlow()
        initView()
        bindState()
        initData()
        return v.root
    }

    abstract fun bindState()

    private fun initStateFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestFlow.collect{
                    if(it.request){
                        Log.i("===","请求开始")
                    }else if(it.complete){
                        Log.i("===","请求完成")
                    }else if (it.error){
                        Log.i("===","错误")
                    }
                }
            }
        }
    }

    abstract fun initData()

    abstract fun initView()
}